/**
 * Created by deng on 2014/8/14.
 */
/****************************
 lab模块的js代码
 ****************************/


$(document).ready(function() {
    $("[data-toggle='tooltip']").tooltip();
    main.init();
    $('#userModal').on('hidden.bs.modal', function(e) {
        $('#userModal .modal-content').empty();
    });
});

//初始化的声明
var util = (function() {
    var changeNav = function(object) {
        $(object).siblings().attr("class","");
        $(object).attr("class","active");
    };

    return {
        changeNav : changeNav
    }
})();

var domFactory = (function() {
    var jDom = function(name,options,data) {
        var dom = $('<' + name +'>' + '</' + name + '>');
        if(options) {
            $.each(options,function(k,v) {
                dom.attr(k,v);
            });
        }
        if(data) {
            dom.append(data);
        }
        return dom;
    };

    var defaultPanel = function(options) {
        if(options) {
            options.class = ('panel panel-default ' + options.class);
            return jDom('div',options);
        } else {
            return jDom('div',{
                class : 'panel panel-default'
            });
        }
    };

    var panelHead = function(data) {
        return jDom('div', {
            class : 'panel-heading'
        },data);
    };

    var panelBody = function() {
        return jDom('div',{
            class : 'panel-body'
        });
    };

    var tableDom = function(options,type) {
        var table = jDom('table',options);
        if(type === 'responsive') {
            var div = jDom('div', {
                class: 'table-responsive'
            });
            div.append(table);
            return div;
        } else {
            return table;
        }
    };

    var theadDom = function(options,data) {
        var thead = jDom('thead',options);
        var tr = trDom(data);
        thead.append(tr);
        return thead;
    };

    var tbodyDom = function(options,datas) {
        var tbody = jDom('tbody',options);
        $.each(datas,function(k,v) {
            tbody.append(trDom(v));
        });
        return tbody;
    };

    var trDom = function(data,options) {
        var tr = jDom('tr',options);
        $.each(data,function(k,v) {
            tr.append(jDom('td',{},v));
        });
        return tr;
    };

    var form = function(options) {
        if(options) {
            options.class += '';
            options.role = 'form';
            return jDom('form',options);
        } else {
            return jDom('form');
        }
    };

    var fieldset = function(data,options) {
        var div = jDom('fieldset',options);
        $.each(data,function(k,v) {
            var formgroup = jDom('div',{
                class : 'form-group'
            });
            $.each(v,function(a,b) {
                jDom(a, b.options, b.data).appendTo(formgroup);
            });
            formgroup.appendTo(div);
        });
        return div;
    };

    return {
        jDom : jDom,
        defaultPanel : defaultPanel,
        panelHead : panelHead,
        panelBody : panelBody,
        tableDom : tableDom,
        theadDom : theadDom,
        tbodyDom : tbodyDom,
        form : form,
        fieldset : fieldset
    };
})();

/*
 modal框的生成
 对外提供两个方法：
 init(id,type),
 remove(id)
 */
var modal = (function(dom){

    var init = function(id,type) {
        var modalDiv = modal(id,type);
        modalDiv.on('hidden.bs.modal', function(e) {
            modalDiv.remove();
        });
        return modalDiv;
    };

    var modal = function(id,type) {
        var modal = dom.jDom('div',{
            class : 'modal fade',
            tabindex : '-1',
            role : 'modal',
            'aria-labelledby' : id,
            'aria-hidden' : 'true',
            id : id
        });
        switch(type) {
            case 'lg':
                modal.append(modalDialog({
                    class : 'modal-dialog modal-lg'
                }));
                break;
            case 'sm':
                modal.append(modalDialog({
                    class : 'modal-dialog modal-sm'
                }));
                break;
            case 'cm':
                modal.append(modalDialog({
                    class : 'modal-dialog'
                }));
                break;
        }
        return modal;
    };

    var modalDialog = function(options) {
        var modalDialog = dom.jDom('div',options);
        modalDialog.append(modalContent({
            class : 'modal-content'
        }));
        return modalDialog;
    };

    var modalContent = function(options) {
        var modalContent = dom.jDom('div',options);
        modalContent.append(modalHead());
        modalContent.append(modalBody());
        return modalContent;
    };

    var modalHead = function(options) {
        var head = dom.jDom('div',{
            class : 'modal-header navbar-default'
        });
        if(options) {
            $.each(options, function(k, v) {
                head.attr(k, v);
            });
        };
        var button = dom.jDom('button',{
            type : "button",
            class : "close",
            'data-dismiss' : "modal"
        },'<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>');
        head.append(button);
        return head;
    };

    var modalNavRight = function(id,options) {
        var a = dom.jDom('a',{
            href : '#'
        },'x');
        var li = dom.jDom('li',{} , a);
        var ul = dom.jDom('ul',{
            class : 'nav navbar-nav nav-bar-right'
        },li);
        li.click(function() {
            $(modalID).modal('hide');
        });
        if (options) {
            $.each(options, function(k, v) {
                ul.attr(k, v);
            });
        }
        return ul;
    };

    var modalBody = function(options) {
        var body = dom.jDom('div', {
            class: 'modal-body'
        });
        if (options) {
            $.each(options, function (k, v) {
                body.attr(k, v);
            });
        }
        return body;
    };

    return {
        init : init
    }
})(domFactory);

/*
 “我的”的模态框的定义
 */
var myModal = (function() {
    var head;
    var body;
    var init = function() {
        var modalDiv = modal.init('myModal','lg');
        head = modalDiv.find('.modal-header');
        body = modalDiv.find('.modal-body');
        var ul = domFactory.jDom('ul',{
            class : 'nav navbar-nav navbar-left'
        });
        showNav(ul,{
            '今日的事' : showToday,
            '我的日程' : showSchedule
        });
        var nav = domFactory.jDom('nav',{
            class : 'navbar-collapse collapse row'
        }).append(ul);
        head.append(nav);
        $('body').append(modalDiv);
        $('#myModal ul li:first').trigger('click');
    };

    var showNav = function(ul,data) {
        $.each(data,function(k,v) {
            var li = ($('<li><a href="#">'+ k +'</a></li>'))
            li.click(function() {
                v(li);
            });
            ul.append(li);
        });
    };

    var showToday = function(obj) {
        util.changeNav(obj);
        clearBody();
        today().appendTo(body).fadeIn('slow');
    };

    var showSchedule = function(obj) {
        util.changeNav(obj);
        clearBody();
        schedule().appendTo(body).show();
        initCalendar($('#calendar'));
    };

    var getTodayEvents = function() {
        var events;
        //ajax
        return events;
    }

    var clearBody = function() {
        $(body).empty();
    };

    var today = function() {
        var today = $('<div class="" id="today" style="display:none">Today\'s event!</div>');
        return today;
    };

    var schedule = function() {
        var schedule = $('<div class="row" id="schedule" stlye="display:none"></div>');
        schedule.append($('<div class="col-md-8" id="calendar"></div>'));
        return schedule;
    };

    var initCalendar = function(divObject) {
        divObject.fullCalendar({
            // put your options and callbacks here
            header: {
                left:   'prev,next today',
                center: 'title',
                right:  'month,agendaWeek,agendaDay'
            },
            buttonText: {
                today:    '今天',
                month:    '月',
                week:     '周',
                day:      '日'
            },
            lang: 'zh-CN',
            selectable: true,
            selectHelper: true,
            select: function(start, end) {
                var title = prompt('Event Title:');
                var eventData;
                if (title) {
                    eventData = {
                        title: title,
                        start: start,
                        end: end
                    };
                    divObject.fullCalendar('renderEvent', eventData, true); // stick? = true
                }
                divObject.fullCalendar('unselect');
            },
            editable: true,
            dayClick: function(date, jsEvent, view) {

            },
            eventClick: function(calEvent, jsEvent, view) {
                alert(jsEvent);
            },
            events: {
                url: '../testAjax/get-events.php',
                error: function() {
                    $('#calendar_error').show();
                }
            }
            //color: 'yellow',    an option!
            //textColor: 'black' // an option!
        });
    };

    return {
        init : init
    }
})();


var userModal = (function() {
    /*
     用户点击设置时初始化一个模态框
     用户推出模态框，模态框消失，并在body中remove().
     */
    var userContent = '#userModal .modal-content';
    var userBody = '#userModal .modal-body';
    var init = function(){
        var head = modal.modalHead({
            class : 'modal-header'
        });
        var nav = modal.modalNav();
        nav.append(modal.modalNavLeft({
            个人设置 : showPersonal,
            用户设置 : showAccount
        }));
        nav.append(modal.modalClose('#userModal'));
        head.append(nav);
        var body = modal.modalBody({
            class : 'modal-body'
        });
        $(userContent).append(head).append(body);
        showPersonal($(userContent + ' ul li:first'));
    };

    var showPersonal = function(object) {
        navItemActive(object);
        clearBody();
        var body = $(userBody);
        var form = horizontalForm({
            title : '个人设置',
            style : '',
            input : [
                {
                    name : '姓名:',
                    attr : {
                        type : 'text',
                        name : 'name',
                        placeHolder : 'Name'
                    }
                },
                {
                    name : 'Email:',
                    attr : {
                        type : 'email',
                        name : 'email',
                        placeHolder : 'email'
                    }
                },
                {
                    name : '个人主页:',
                    attr : {
                        type : 'url',
                        name : 'url',
                        placeHolder : 'URL'
                    }
                },
                {
                    name : '研究机构:',
                    attr : {
                        type : 'text',
                        name : 'institution',
                        placeHolder : 'institution'
                    }
                }
            ]
        });
        body.append(form);
    };

    var showAccount = function(object) {
        navItemActive(object);
        clearBody();
        var body = $(userBody);
        var form = horizontalForm({
            title : '用户设置',
            style : '',
            input : [
                {
                    name : '原密码:',
                    attr : {
                        type : 'password',
                        name : 'oldPassword'
                    }
                },
                {
                    name : '新密码:',
                    attr : {
                        type : 'password',
                        name : 'newPassword'
                    }
                },
                {
                    name : '重复:',
                    attr : {
                        type : 'password',
                        name : 'newRetype'
                    }
                }
            ]
        });
        body.append(form);
    };

    var clearBody = function() {
        $(userBody).empty();
    };

    return {
        init : init
    };
})();


/*
 进入主页后的实验室显示
 */
var main = (function() {
    var email;

    var init = function() {
        email = getCookie('email');
        if(email) {
            $.ajax({
                type : 'GET',
                url : '../testAjax/lab.php',
                data : {
                    email : email
                },
                dataType : 'json',
                success : function(response) {
                    var status = response.status;
                    var data;
                    if(status === 'ok') {
                        data = response.data;
                        var user = data.user;
                        var items = data.lab;
                        showItems(items);
                        lab.showItems(items);
                    };
                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + textStatus + errorThrown);
                }
            })
        } else {
            alert("未登录！");
            window.location.href = 'login.php';
        }
    };

    var userInf = function(data) {

    };

    var showItems = function(items) {
        var ul = $('#lab-all ul:first');
        $.each(items,function(k,v) {
            var li = $('<li class="lab-li"></li>');
            var div = domFactory.jDom('div',{
                class : 'lab-item',
                'data-id' : v.id
            });
            div.css('background-image','url('+ v.url +')');
            var span = $('<span>' + v.name + '</span>');
            div.bind({
                'click' : function() {
                    lab.init(v.id);
                }
            });
            div.append(span).appendTo(li);
            ul.append(li);
        });
        var li = domFactory.jDom('li',{
            class : 'lab-li',
            'data-toggle' : 'modal',
            'data-target' : '#newLab'
        },'<div class="lab-item">新的实验室</div>');
        //var li = $('<li class="lab-li"><div class="lab-item">新的实验室</div></li>');
        li.click(function() {
            newLab.init();
        });
        ul.append(li);
    };

    return {
        init : init
    };
})();

var newLab = (function() {

    var init = function() {
        var modalDiv = modal.init('newLab','cm');
        var head = modalDiv.find('.modal-header').remove();
        var body = modalDiv.find('.modal-body');
        body.append(form());
        $('body').append(modalDiv);
    };

    var form = function() {
        var form = domFactory.jDom('form',{
            class : '',
            role : 'form'
        });
        form.append('<legend>创建实验室</legend>');
        var fieldset = domFactory.fieldset([
            {
                label : {
                    data : '实验室名称'
                },
                input : {
                    options : {
                        type : 'text',
                        class : 'form-control',
                        id : 'name',
                        placeHolder : '实验室名称'
                    }
                }
            } ,
            {
                label : {
                    data : '实验室介绍'
                },
                textarea : {
                    options : {
                        class: 'form-control',
                        id: '',
                        rows: '5',
                        placeHolder: '实验室介绍'
                    }
                }
            },
            {
                button : {
                    options : {
                        type : 'button',
                        class : 'btn btn-primary form-control'
                    },
                    data : '保存'
                }
            }
        ]);
        form.append(fieldset);
        return form;
    };

    return {
        init : init
    }
})();

var lab = (function(){

    var init = function(labID) {
        //把labID存入cookie
        setCookie('lab',labID);
        //根据labID调整数据
        //在主界面显示实验室内部界面
        showLab();
        showNotice();
    };

    var showLab = function() {
        $('#lab-all').slideUp(function() {
            $('#lab').fadeIn('slow');
        });
    };

    var showItems = function(items) {
        $.each(items,function(k,v) {
            var li = $('<li class="lab-item"></li>');
            var div = $('<div class="image"></div>');
            var span = $('<span>' + v.name + '</span>');
            li.attr('data-id',v.id);
            div.css('background-image','url('+ v.url +')');
            li.append(div).append(span);
            li.click(function() {
                lab.init(v.id);
            });
            $('#lab ul:first').append(li);
        })
    };

    var showNotice = function(obj) {
        util.changeNav(obj);
        module_notice.init();
    };

    var showDocument = function(obj) {
        util.changeNav(obj);
        module_document.init();
    };

    var showInventory = function(obj) {
        util.changeNav(obj);
        module_inventory.init();
    };

    var showShareEquipment = function(obj) {
        util.changeNav(obj);
        module_shareEquipment.init();
    };


    return {
        init : init,
        showItems : showItems,
        showNotice : showNotice,
        showDocument : showDocument,
        showInventory : showInventory,
        showShareEquipment : showShareEquipment
    }
})();

var module = (function() {

    var moduleContent = '#module-content';

    var init = function() {
        $(moduleContent).empty();
    };

    var getModuleContent = function() {
        return moduleContent;
    };

    return {
        getModuleContent : moduleContent,
        init : init
    }
})();

var module_notice = (function(module) {

    var init = function() {
        //初始化module，即清空内部
        module.init();
        //从后台去到数据并将数据放到对应的模块中.
        getNotice();
    };

    var getNotice = function() {
        /*
         取到实验室最新的动态.
         */
        $.ajax({
            type : "GET",
            url : '../testAjax/notice.php',
            data : {
                lab : getCookie('lab')
            },
            dataType : 'json',
            beforeSend : function(XHR) {
                var div = domFactory.jDom('div',{
                    class : 'row',
                    id : 'notice'
                });
                div.append(notice()).append(sendNotice()).appendTo($(module.getModuleContent));
            },
            success : function(response) {
                //把数据传给模块的创造方法.
                if (response.status === 'ok') {
                    noticeItem(response.data);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    };

    var noticeItem = function(data) {
        var body = $('#notice .panel');
        var ul = domFactory.jDom('ul',{
            class : 'list-group'
        });
        $.each(data,function(k,v) {
            var li = domFactory.jDom('li',{
                class : 'list-group-item'
            }, v.name + ' : ' + v.content);
            ul.append(li);
        });
        body.append(ul);
    };

    var notice = function() {
        var div = domFactory.jDom('div',{
            class : 'col-md-8',
            id : 'notice'
        });
        var panel = domFactory.defaultPanel();
        var panelHead = domFactory.panelHead('最新动态');
        //var panelBody = domFactory.panelBody();
        panel.append(panelHead).appendTo(div);
        return div;
    };

    var sendNotice = function() {
        var div = domFactory.jDom('div',{
            class : 'col-md-4'
        });
        var form = domFactory.jDom('form',{});
        var legend = $('<legend><strong>发布消息</strong></legend>');
        var textarea = domFactory.jDom('textarea',{
            class : 'form-control',
            rows : '5',
            placeHolder : '推送你的消息到实验室'
        });
        var button = createButton();
        form.append(legend).append(textarea).append(button).appendTo(div);
        return div;
    };

    var createButton = function() {
        var div = domFactory.jDom('div',{
            class : 'send'
        });
        var button = domFactory.jDom('button',{
            class : 'btn btn-success btn-xs btn-block',
            type : 'button'
        },'推送');

        button.click(function() {
            $.ajax({

            });
        });
        div.append(button);
        return div;
    };

    return {
        init : init
    }
})(module);

var module_document = (function(module) {

    var init = function() {
        module.init();
        var div = domFactory.jDom('div',{
            class : '',
            id : 'document'
        });
        div.append(panelAll()).append(panelSelf()).appendTo($(module.getModuleContent));
    };

    var panel = function() {
        var div = domFactory.defaultPanel();
        var head = domFactory.panelHead();
        var body = domFactory.panelBody();
        body.append(panelAll()).append(panelSelf());
        div.append(head).append(body);
        return div;
    };

    var panelAll = function() {
        var div = domFactory.jDom('div',{
            class : 'col-md-6'
        });
        var panel = domFactory.defaultPanel();
        var head = domFactory.panelHead('公共');
        var body = domFactory.panelBody();
        panel.append(head).append(body).appendTo(div);
        return div;
    }

    var panelSelf = function() {
        var div = domFactory.jDom('div',{
            class : 'col-md-6'
        });
        var panel = domFactory.defaultPanel();
        var head = domFactory.panelHead('私人的');
        var body = domFactory.panelBody();
        panel.append(head).append(body).appendTo(div);
        return div;
    }

    return {
        init : init
    }

})(module);

var module_inventory = (function(module) {

    var init = function() {
        module.init();
        var div = domFactory.jDom('div',{
            class : '',
            id : 'inventory'
        });
        div.append(panel()).appendTo($(module.getModuleContent));
    };

    var panel = function() {
        var div = domFactory.defaultPanel();
        var head = domFactory.panelHead('库存');
        var body = domFactory.panelBody();
        body.append(table());
        div.append(head).append(body);
        return div;
    };

    var table = function() {
        var div = domFactory.tableDom({
            class : 'table table-striped table-hover'
        },'responsive');
        var table = div.find('table');
        var thead = domFactory.theadDom({},[
            '#',
            '物品名称',
            '提供商',
            '类型',
            '单价',
            '总库存',
            '剩余库存'
        ]);
        var tbody = domFactory.tbodyDom({},{});
        table.append(thead).append(tbody);
        return div;
    };

    return {
        init : init
    }
})(module);

var module_shareEquipment = (function(module) {

    var init = function() {
        module.init();
        var div = domFactory.jDom('div',{
            class : '',
            id : 'share-equipment'
        });
        div.append(panel()).appendTo($(module.getModuleContent));
    };

    var panel = function() {
        var div = domFactory.defaultPanel();
        var head = domFactory.panelHead('全部设备');
        var body = domFactory.panelBody();
        body.append(equipmentDiv([
            {
                name : '1',
                id : '1',
                url : '../images/equipment-1.jpg'
            },
            {
                name : '2',
                id : '2',
                url : '../images/equipment-2.jpg'
            },
            {
                name : '3',
                id : '3',
                url : '../images/equipment-3.jpg'
            }
        ]));
        div.append(head).append(body);
        return div;
    };

    var equipmentDiv = function(data) {
        var div = domFactory.jDom('div',{
            class : 'row'
        });
        $.each(data,function(k,v) {
            var wrap = domFactory.jDom('div',{
                class : 'col-xs-6 col-md-3'
            });
            var a = domFactory.jDom('a',{
                href : '#',
                class : 'thumbnail',
                'data-id' : v.id,
                'data-name' : v.name,
                'data-toggle' : 'popover',
                'title' : 'Test',
                'data-content' : '介绍'
            });
            var img = domFactory.jDom('div',{
                class : 'equipment-item'
            });
            img.css('background-image', 'url("' + v.url + '")');
            a.append(img);
            wrap.append(a).appendTo(div);
        });
        return div;
    };

    return {
        init : init
    }

})(module);